package network_programming.np1_socket_and_serversocket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServerDemo {
    private int port;       // 服务器端口号
    TCPServerDemo(int port) {
        this.port = port;
    }
    TCPServerDemo() {
        this(9090);
    }
    public void start() {
        // ServerSocket ss = new ServerSocket(port, 3);     // 第二个参数用于设置连接请求队列的长度
        try (ServerSocket ss = new ServerSocket(port); Socket socket = ss.accept()) {
//            ss.accept();    // 等待客户连接到此套接字，并返回对应的socket对象，阻塞式
            InputStream is = socket.getInputStream();   // 获取输入流
            byte[] buffer = new byte[1024];     // 缓冲区
            int len = is.read(buffer);
            System.out.println("接收到的数据：" + new String(buffer, 0, len));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TCPServerDemo tsd = new TCPServerDemo();
        tsd.start();
    }
}
